package org.hongbo.springbootebsapi.service.login.impl;

import oracle.jdbc.OracleTypes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.CallableStatementCallback;
import org.springframework.jdbc.core.CallableStatementCreator;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;


import javax.servlet.http.HttpServletRequest;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.hongbo.springbootebsapi.service.login.ILoginService;


/**
 * Created by 洪波 on 2018/04/20
 */
@Service
public class LoginServiceImpl implements ILoginService {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoginServiceImpl.class);

    @Autowired
    protected JdbcTemplate jdbcTemplate;


    @Autowired
    private HttpServletRequest request;

    @Autowired
    private ILoginService loginService;

    @Override
  public boolean verifyLogin(String username ,String password){

      boolean login = validateEBSLogin(username,password);
      return login;

  }

    /**
     * 参考：http://sunbin123.iteye.com/blog/1007556
     * @param username
     * @param password
     */
    @Override
  public boolean validateEBSLogin(String username, String password){
        String callValidLoginSql = "{? = call sys.diutil.bool_to_int(fnd_user_pkg.validatelogin(?,?))}";
        String validLoginSql = "BEGIN  :1 := sys.diutil.bool_to_int(fnd_user_pkg.validatelogin(:2,:3));END;";
        Boolean loginResult = false;



        String returnValue = (String) jdbcTemplate.execute(
              new CallableStatementCreator() {
                  @Override
                  public CallableStatement createCallableStatement(Connection con) throws SQLException {
                      CallableStatement cs = con.prepareCall(validLoginSql);
                      cs.setString(2, username);// 设置输入参数的值
                      cs.setString(3,password);
//                      cs.registerOutParameter(1, OracleTypes.VARCHAR);// 注册输出参数的类型
                      cs.registerOutParameter(1, OracleTypes.VARCHAR);// 注册输出参数的类型
                      return cs;
                  }
              }, new CallableStatementCallback() {
                  @Override
                  public Object doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException {
                      cs.execute();
                      LOGGER.info("执行函数返回值 "+cs.getString(1));
                      return cs.getString(1);// 获取输出参数的值
                  }
              });

        LOGGER.info("jdbcTemplate执行结果  "+returnValue);

        if("1".equals(returnValue)){
            loginResult = true;
        }

        return loginResult;
  }


  @Override
  public String getUserIdByName(String userName){
      String userId=null;
      userName.toUpperCase();
      userId = String.valueOf( jdbcTemplate.queryForObject("SELECT fu.USER_ID FROM fnd_user fu WHERE fu.USER_NAME =? ", new Object[] {userName.toUpperCase()}, String.class));

      return userId;
  }
    @Override
    public String getLoginUserId(){
        String userId=null;
        userId = String.valueOf(jdbcTemplate.queryForObject("SELECT fnd_global.user_id FROM dual",Integer.class));
        return userId;
    }

    @Override
  public String getLoginUserName(){
        String loginUserName = null;

        loginUserName = String.valueOf(jdbcTemplate.queryForObject("SELECT fnd_global.user_name FROM dual",String.class));
        return loginUserName;
  }

    @Override
    public String getEmployeeId(){
        String employeeId = null;
        employeeId = String.valueOf(jdbcTemplate.queryForObject("SELECT fnd_global.employee_id FROM dual",Integer.class));
        return employeeId;
    }

    @Override
    public String getLoginId(){
        String loginId = null;
        loginId = String.valueOf(jdbcTemplate.queryForObject("SELECT fnd_global.login_id FROM dual",Integer.class));
        return loginId;
    }

    @Override
  public String getCurrentRespId(){
      String respId = null;
      respId = String.valueOf(jdbcTemplate.queryForObject("SELECT fnd_global.resp_id FROM dual",Integer.class));
      return respId;
  }

    @Override
  public String getCurrentRespApplId(){
      String respApplId = null;
      respApplId = String.valueOf(jdbcTemplate.queryForObject("SELECT fnd_global.resp_appl_id FROM dual",Integer.class));
      return respApplId;
  }

    @Override
    public String getRespName(){
      String respName = null;
      respName =String.valueOf(jdbcTemplate.queryForObject("SELECT fnd_global.resp_name FROM dual",String.class));
      return respName;
    }

    @Override
  public String getOrgId(){
        String orgId =null;
        orgId = String.valueOf(jdbcTemplate.queryForObject("SELECT fnd_profile.value('ORG_ID')  FROM DUAL",Integer.class));
        return orgId;
  }



    @Override
    public Set<String> getAllUrl() {
        Set<String> result = new HashSet<String>();
        WebApplicationContext wc = (WebApplicationContext) request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        RequestMappingHandlerMapping bean = wc.getBean(RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = bean.getHandlerMethods();
        for (RequestMappingInfo rmi : handlerMethods.keySet()) {
            PatternsRequestCondition pc = rmi.getPatternsCondition();
            Set<String> pSet = pc.getPatterns();
            result.addAll(pSet);
        }
        return result;
    }

}
